package com.southwind.demo3;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Ticket {
    //剩余球票
    private int surpluCount = 15;
    //已售出球票
    private int outCount = 0;
    private Lock lock = new ReentrantLock();

    public void sale() {

        while (surpluCount > 0) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (surpluCount == 0) {
                return;
            }
//            lock.lock();
            synchronized (Ticket.class){
                surpluCount--;
                outCount++;
                if (surpluCount == 0) {
                    System.out.println(Thread.currentThread().getName() + "售出第" + outCount + "张票，球票已售罄");
                } else {
                    System.out.println(Thread.currentThread().getName() + "售出第" + outCount + "张票，剩余" + surpluCount + "张票");
                }
            }

//            lock.unlock();
        }

    }
}
